package com.atung.merchant.config.mybatis;

import com.atung.merchant.dto.AuthUserEntity;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    // 插入时自动填充
    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前时间的Instant对象
        Instant now = Instant.now();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将Instant对象转换为String
        String nowAsString = formatter.format(now.atZone(ZoneId.systemDefault()));
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthUserEntity authUserEntity = (AuthUserEntity) (authentication.getPrincipal());
        // 创建时间
        this.strictInsertFill(metaObject, "creatorTime", () -> nowAsString, String.class);
        // 创建人
        this.strictInsertFill(metaObject, "creatorId", () -> authUserEntity.getName(), String.class);
    }

    // 更新时自动填充
    @Override
    public void updateFill(MetaObject metaObject) {
        Instant now = Instant.now();

        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 将Instant对象转换为String
        String nowAsString = formatter.format(now.atZone(ZoneId.systemDefault()));
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthUserEntity authUserEntity = (AuthUserEntity) (authentication.getPrincipal());

        // 更新时间
        this.strictUpdateFill(metaObject, "modifierTime", () -> nowAsString, String.class);
        //修改人
        this.strictInsertFill(metaObject, "modifierId",() -> authUserEntity.getName(), String.class);
    }

}
